package com.lsyw.intergrate.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.common.StringUtil;
import com.lsyw.intergrate.entity.Massif;
import com.lsyw.intergrate.entity.MassifUser;
import com.lsyw.intergrate.entity.UnopDept;
import com.lsyw.intergrate.entity.common.LoginInfo;
import com.lsyw.intergrate.entity.qo.LoginQo;
import com.lsyw.intergrate.service.MassifService;
import com.lsyw.intergrate.service.MassifUserService;
import com.lsyw.intergrate.service.SysUserService;
import com.lsyw.intergrate.service.UnopDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.lsyw.intergrate.common.MybatisPlus.ColumnResolver.massifUserCR;
import static com.lsyw.intergrate.common.Result.errorResult;
import static com.lsyw.intergrate.common.Result.successResult;
import static com.lsyw.intergrate.common.util.PositionUtil.getDistance4;

/**
 * <p>
 * 移动端前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-04-18
 */
@Api(tags = "移动端接口")
@RestController
@RequestMapping("/app")
public class APPController {

    @Autowired
    private UnopDeptService unopDeptService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MassifUserService massifUserService;

    @Autowired
    private MassifService massifService;

    /**
     * 根据经纬度获取最近的工地
     */
    @GetMapping("/get-massif-by-jw")
    @ApiOperation(value = "根据经纬度获取最近的工地", notes = "根据经纬度获取最近的工地", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jd", value = "jd", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "wd", value = "wd", required = true, paramType = "query", dataType = "String")
    })
    public Result getByMassifUserId(String wd, String jd) {
        LambdaQueryWrapper<Massif> lambda = new QueryWrapper<Massif>().lambda();
        lambda.eq(Massif::getDelFlag, 0);
        List<Massif> list = this.massifService.list(lambda);
        List<Map<String, Double>> mapList = new ArrayList<>();
        Map<String, Double> map = new HashMap<>();
        for (Massif massif : list) {

            String massifJD = massif.getJd();
            String massifWD = massif.getWd();
            Double distance = getDistance4(Double.parseDouble(massifJD), Double.parseDouble(massifWD), Double.parseDouble(jd), Double.parseDouble(wd));
            map.put(massif.getId(), distance);
            //  mapList.add(map);
        }
        Map<String, Double> sortedMap = new LinkedHashMap<>();
        map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

        Iterator<Map.Entry<String, Double>> iterator = map.entrySet().iterator();
        List<Massif> massifList = new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<String, Double> entry = iterator.next();
            String id = entry.getKey();
            System.out.println("第一个值是：" + id);
            Massif massif = this.massifService.getById(id);
            massifList.add(massif);

        }
        return Result.successResult(massifList);
    }

    /**
     * 比对经纬度获取距离
     */
    @GetMapping("/get-massif-by-jl")
    @ApiOperation(value = "比对经纬度获取距离", notes = "比对经纬度获取距离", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jd", value = "车所在经度", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "wd", value = "车所在纬度", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "routeJd", value = "路线经度", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "routeWd", value = "路线纬度", required = true, paramType = "query", dataType = "String"),
    })
    public Result getMassifByJL(String wd, String jd, String routeJd, String routeWd) {
        Double distance = getDistance4(Double.parseDouble(wd), Double.parseDouble(jd), Double.parseDouble(routeJd), Double.parseDouble(routeWd));
        Double aDouble = new Double(Math.abs(distance.doubleValue()));
        return Result.successResult(aDouble);
    }


    /**
     * 获取司机信息
     */
    @GetMapping("/get-by-massifUser-id")
    @ApiOperation(value = "获取司机信息", notes = "获取司机信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    public Result getByMassifUserId(String id) {
        return Result.successResult(massifUserService.getById(id));
    }

    /**
     * 修改司机信息
     */
    /**
     * 修改
     */
    @PostMapping("/update/massifUser")
    @ApiOperation(value = "修改司机信息", notes = "修改司机信息", httpMethod = "POST")
    public Result updateById(@RequestBody MassifUser massifUser) {
        massifUser.setDelFlag(0);
        massifUser.setGmtModified(new Date());
        massifUserService.updateById(massifUser);
        return Result.successResult(null);
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST")
    @Transactional
    public Result login(@RequestBody LoginQo loginQo) {
        String phone = loginQo.getPhone();
        //  String password = loginQo.getPassword();
        //判断是否为空
        if (StringUtil.isEmpty(phone)) {
            return errorResult(null, "用户名、密码不能为空");
        }
        if (StringUtil.isEmpty(loginQo.getRole())) {
            return errorResult(null, "用户角色不能为空");
        }

        QueryWrapper<MassifUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(massifUserCR.columnToString(MassifUser::getPhone), phone)
                .eq(massifUserCR.columnToString(MassifUser::getIsDelete), 0)
                .eq(massifUserCR.columnToString(MassifUser::getRole), loginQo.getRole());
        List<MassifUser> list = this.massifUserService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)&&loginQo.getRole().equals("0")) {
            //没有就新增
            MassifUser massifUser = new MassifUser();

            massifUser.setPhone(phone);
            massifUser.setRole(loginQo.getRole());
            massifUser.setCreatedTime(new Date());
            massifUser.setUpdatedTime(new Date());
            massifUser.setIsDelete(0);
            massifUser.setDelFlag(0);
            massifUserService.save(massifUser);
            list = this.massifUserService.list(queryWrapper);
        }else if(CollectionUtils.isEmpty(list)){
            return errorResult(null, "登录失败，该角色用户不存在！");
        }

        MassifUser massifUser = list.get(0);
        String id = massifUser.getId();
        //登录失败
        if (StringUtil.isEmpty(id)) {
            return errorResult(null, "用户名或密码错误。");
        }
        StpUtil.login(id, "PC");
        //获取token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();


        if (true) {
            return successResult(new LoginInfo(massifUser, tokenInfo));
        } else {
            return errorResult(null);
        }
    }
    /**
     * 查询列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询部门列表", notes = "查询部门列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "查询条件", required = true, paramType = "query", dataType = "String")
    })
    public Result list(String name) {
        LambdaQueryWrapper<UnopDept> lambda = new QueryWrapper<UnopDept>().lambda();
        if (!StringUtils.isEmpty(name)) {
            lambda.like(UnopDept::getName, "%" + name + "%");
        }
        lambda.eq(UnopDept::getIsBf, 2);
        unopDeptService.list(lambda);
        return Result.successResult(unopDeptService.list(lambda));
    }


}
